package asia.lxq.cic.util;

import asia.lxq.cic.config.GlobalConfig;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Calendar;
import java.util.Map;

public class TokenUtil {
    public static String tokenGenerator(Map<String,String> payload,int expired){
        JWTCreator.Builder builder = JWT.create();
        var calendar= Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,expired);
        payload.forEach(builder::withClaim);
        builder.withExpiresAt(calendar.getTime());
        return builder.sign(Algorithm.HMAC256(GlobalConfig.TOKEN_SECRET));
    }
    public static void parseToken(String token){
        var verifier=JWT.require(Algorithm.HMAC256(GlobalConfig.TOKEN_SECRET)).build();
        var decodedWT=verifier.verify(token);//doesn't have a valid JSON format.
        Map<String, Claim> claims = decodedWT.getClaims();
        claims.forEach((k,v)-> System.out.println("key="+k+" value="+v.asString()));
    }
    public static Map<String, Claim> verifyToken(String token){
        var verifier=JWT.require(Algorithm.HMAC256(GlobalConfig.TOKEN_SECRET)).build();
        var decodedWT=verifier.verify(token);
        return decodedWT.getClaims();
    }
}
